package com.demo.thread;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenhe17596 on 2017/6/20.
 */
public class ThreadPoolExecutorTest {

    public void ThreadPool(){
        //可缓存线程池
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i=0; i<10; i++){
            final int index = i;
            try{
                Thread.sleep(index*1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            cachedThreadPool.execute(new Runnable() {
                public void run() {
                    System.out.println(index);
                }
            });
        }
    }

    public void ThreadPool1(){
        //定长线程池
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        for (int i =0; i<10; i++){
            final int index = i;
            fixedThreadPool.execute(new Runnable() {
                public void run() {
                    try {
                        System.out.println(index);
                        Thread.sleep(2000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public void ThreadPool2(){
        //定长线程池，延迟3秒执行
        ScheduledExecutorService scheduledThreadPool =Executors.newScheduledThreadPool(5);
        scheduledThreadPool.schedule(new Runnable() {
            public void run() {
                System.out.println("delay 3 seconds " + new Date());
            }
        },3, TimeUnit.SECONDS);
    }

    public void ThreadPool3(){
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            public void run() {
                System.out.println("delay 1 seconds, and excute every 3 seconds  " + new Date());
            }
        },1,2,TimeUnit.SECONDS);
    }
    public static void main(String[] args){
        ThreadPoolExecutorTest threadPool = new ThreadPoolExecutorTest();
        //threadPool.ThreadPool();
        //threadPool.ThreadPool1();
        //threadPool.ThreadPool2();
        threadPool.ThreadPool3();
    }
}
